<html><head><meta charset="utf-8"><title>42 常用的 Lambda 表达式使用场景解析和应用    -慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">


<div class="main-con hide-menu">
    <!-- 左侧菜单 & 索引 -->
    
    <div class="right-content" style="padding-left: 0px;">
        <div class="container clearfix" id="top" style="width: 1134px; display: block;">
            
            
            <div class="center_con js-center_con l" style="width: 1134px;">
                <div class="article-con">
                                            <!-- 买过的阅读 -->
                        

                    
                    <div class="art-title" style="margin-top: 0px;">
                        42 常用的 Lambda 表达式使用场景解析和应用    
                    </div>
                    <div class="art-info clearfix">
                        
                        <span class="l">
                            更新时间：2019-11-27 10:56:25
                        </span>
                    </div>
                    <div class="art-top">
                                                <img src="https://img3.mukewang.com/5ddde5d5000138f106400359.jpg" alt="">
                                                                        <div class="famous-word-box">
                            <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                            <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                            <div class="famous-word">耐心和恒心总会得到报酬的。<p class="author">——爱因斯坦</p></div>
                        </div>
                                            </div>
                    <div class="art-content js-lookimg">
                        <div id="article_content">
                            <div class="cl-preview-section"><h2 id="引导语" style="font-size: 30px;">引导语</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们日常工作中，Lambda 使用比较多的场景，就是 List 或 Map 下的 Lambda 流操作，往往几行代码可以帮助我们实现多层 for 循环嵌套的复杂代码，接下来我们把 Lambda 流的常用方法用案列讲解一下。</p>
</div><div class="cl-preview-section"><h2 id="数据准备" style="font-size: 30px;">1 数据准备</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本文演示的所有代码都在 demo.eight.LambdaExpressionDemo 中，首先我们需要准备一些测试的数据，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token annotation punctuation">@Data</span>
<span class="token comment">// 学生数据结构</span>
<span class="token keyword">class</span> <span class="token class-name">StudentDTO</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span> <span class="token punctuation">{</span>

  <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> <span class="token operator">-</span>7716352032236707189L<span class="token punctuation">;</span>

  <span class="token keyword">public</span> <span class="token function">StudentDTO</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token punctuation">}</span>

  <span class="token keyword">public</span> <span class="token function">StudentDTO</span><span class="token punctuation">(</span>Long id<span class="token punctuation">,</span> String code<span class="token punctuation">,</span> String name<span class="token punctuation">,</span> String sex<span class="token punctuation">,</span> Double scope<span class="token punctuation">,</span>
                    List<span class="token operator">&lt;</span>Course<span class="token operator">&gt;</span> learningCources<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>id <span class="token operator">=</span> id<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>code <span class="token operator">=</span> code<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>sex <span class="token operator">=</span> sex<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>scope <span class="token operator">=</span> scope<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>learningCources <span class="token operator">=</span> learningCources<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token comment">/**
   * id
   */</span>
  <span class="token keyword">private</span> Long id<span class="token punctuation">;</span>
  <span class="token comment">/**
   * 学号 唯一标识
   */</span>
  <span class="token keyword">private</span> String code<span class="token punctuation">;</span>
  <span class="token comment">/**
   * 学生名字
   */</span>
  <span class="token keyword">private</span> String name<span class="token punctuation">;</span>

  <span class="token comment">/**
   * 性别
   */</span>
  <span class="token keyword">private</span> String sex<span class="token punctuation">;</span>

  <span class="token comment">/**
   * 分数
   */</span>
  <span class="token keyword">private</span> Double scope<span class="token punctuation">;</span>

  <span class="token comment">/**
   * 要学习的课程
   */</span>
  <span class="token keyword">private</span> List<span class="token operator">&lt;</span>Course<span class="token operator">&gt;</span> learningCources<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token annotation punctuation">@Data</span>
<span class="token comment">// 课程数据结构</span>
<span class="token keyword">class</span> <span class="token class-name">Course</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span> <span class="token punctuation">{</span>

  <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> 2896201730223729591L<span class="token punctuation">;</span>

  <span class="token comment">/**
   * 课程 ID
   */</span>
  <span class="token keyword">private</span> Long id<span class="token punctuation">;</span>

  <span class="token comment">/**
   * 课程 name
   */</span>
  <span class="token keyword">private</span> String name<span class="token punctuation">;</span>

  <span class="token keyword">public</span> <span class="token function">Course</span><span class="token punctuation">(</span>Long id<span class="token punctuation">,</span> String name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>id <span class="token operator">=</span> id<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token comment">// 初始化数据</span>
<span class="token keyword">private</span> <span class="token keyword">final</span> List<span class="token operator">&lt;</span>StudentDTO<span class="token operator">&gt;</span> students <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>StudentDTO<span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token punctuation">{</span>
    <span class="token comment">// 添加学生数据</span>
    <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StudentDTO</span><span class="token punctuation">(</span>1L<span class="token punctuation">,</span><span class="token string">"W199"</span><span class="token punctuation">,</span><span class="token string">"小美"</span><span class="token punctuation">,</span><span class="token string">"WM"</span><span class="token punctuation">,</span><span class="token number">100D</span><span class="token punctuation">,</span><span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>Course<span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token punctuation">{</span>
        <span class="token comment">// 添加学生学习的课程</span>
        <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Course</span><span class="token punctuation">(</span>300L<span class="token punctuation">,</span><span class="token string">"语文"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Course</span><span class="token punctuation">(</span>301L<span class="token punctuation">,</span><span class="token string">"数学"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Course</span><span class="token punctuation">(</span>302L<span class="token punctuation">,</span><span class="token string">"英语"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StudentDTO</span><span class="token punctuation">(</span>2L<span class="token punctuation">,</span><span class="token string">"W25"</span><span class="token punctuation">,</span><span class="token string">"小美"</span><span class="token punctuation">,</span><span class="token string">"WM"</span><span class="token punctuation">,</span><span class="token number">100D</span><span class="token punctuation">,</span>Lists<span class="token punctuation">.</span><span class="token function">newArrayList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StudentDTO</span><span class="token punctuation">(</span>3L<span class="token punctuation">,</span><span class="token string">"W3"</span><span class="token punctuation">,</span><span class="token string">"小名"</span><span class="token punctuation">,</span><span class="token string">"M"</span><span class="token punctuation">,</span><span class="token number">90D</span><span class="token punctuation">,</span><span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>Course<span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token punctuation">{</span>
        <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Course</span><span class="token punctuation">(</span>300L<span class="token punctuation">,</span><span class="token string">"语文"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Course</span><span class="token punctuation">(</span>304L<span class="token punctuation">,</span><span class="token string">"体育"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StudentDTO</span><span class="token punctuation">(</span>4L<span class="token punctuation">,</span><span class="token string">"W1"</span><span class="token punctuation">,</span><span class="token string">"小蓝"</span><span class="token punctuation">,</span><span class="token string">"M"</span><span class="token punctuation">,</span><span class="token number">10D</span><span class="token punctuation">,</span><span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>Course<span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token punctuation">{</span>
        <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Course</span><span class="token punctuation">(</span>301L<span class="token punctuation">,</span><span class="token string">"数学"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Course</span><span class="token punctuation">(</span>305L<span class="token punctuation">,</span><span class="token string">"美术"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">请大家稍微看下数据结构，不然看下面案例跑出来的结果会有些吃力。</p>
</div><div class="cl-preview-section"><h2 id="常用方法" style="font-size: 30px;">2 常用方法</h2>
</div><div class="cl-preview-section"><h3 id="filter">2.1 Filter</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Filter 为过滤的意思，只要满足 Filter 表达式的数据就可以留下来，不满足的数据被过滤掉，源码如下图：<br>
<img class="" src="https://img.mukewang.com/5dd6009100012e5d20500742.png" data-original="//img.mukewang.com/5dd6009100012e5d20500742.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们写了一个 demo，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testFilter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// list 在下图中进行了初始化</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> newList <span class="token operator">=</span> list<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token comment">// 过滤掉我们希望留下来的值</span>
      <span class="token comment">// StringUtils.equals(str,"hello") 表示我们希望字符串是 hello 能留下来</span>
      <span class="token comment">// 其他的过滤掉</span>
      <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>str <span class="token operator">-</span><span class="token operator">&gt;</span> StringUtils<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>str<span class="token punctuation">,</span> <span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token comment">// Collectors.toList() 帮助我们构造最后的返回结果</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestFilter result is {}"</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>newList<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd6007d0001804022520840.png" data-original="//img.mukewang.com/5dd6007d0001804022520840.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><h3 id="map">2.2 map</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">map 方法可以让我们进行一些流的转化，比如原来流中的元素是 A，通过 map 操作，可以使返回的流中的元素是 B，源码如下图：<br>
<img class="" src="https://img.mukewang.com/5dd6006b00015baf20920956.png" data-original="//img.mukewang.com/5dd6006b00015baf20920956.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们写了一个 demo，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism ![图片描述](//img.mukewang.com/5dd600410001e53d19820916.png)  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 得到所有学生的学号</span>
  <span class="token comment">// 这里 students.stream() 中的元素是 StudentDTO，通过 map 方法转化成 String 的流</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> codes <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token comment">//StudentDTO::getCode 是 s-&gt;s.getCode() 的简写</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestMap 所有学生的学号为 {}"</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>codes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">// 运行结果为：TestMap 所有学生的学号为 ["W199","W25","W3","W1"]</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="maptoint">2.3 mapToInt</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">mapToInt 方法的功能和 map 方法一样，只不过 mapToInt 返回的结果已经没有泛型，已经明确是 int 类型的流了，源码如下：<br>
<img class="" src="https://img.mukewang.com/5dd600580001e53d19820916.png" data-original="//img.mukewang.com/5dd600580001e53d19820916.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们写了一个 demo，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testMapToInt</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  List<span class="token operator">&lt;</span>Integer<span class="token operator">&gt;</span> ids <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">mapToInt</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>Integer<span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">+</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token comment">// 一定要有 mapToObj，因为 mapToInt 返回的是 IntStream，因为已经确定是 int 类型了</span>
      <span class="token comment">// 所有没有泛型的，而 Collectors.toList() 强制要求有泛型的流，所以需要使用 mapToObj</span>
      <span class="token comment">// 方法返回有泛型的流</span>
      <span class="token punctuation">.</span><span class="token function">mapToObj</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>s<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestMapToInt result is {}"</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>ids<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 计算学生总分</span>
  Double sumScope <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">mapToDouble</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>s<span class="token punctuation">.</span><span class="token function">getScope</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token comment">// DoubleStream/IntStream 有许多 sum（求和）、min（求最小值）、max（求最大值）、average（求平均值）等方法</span>
      <span class="token punctuation">.</span><span class="token function">sum</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestMapToInt 学生总分为： is {}"</span><span class="token punctuation">,</span> sumScope<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">TestMapToInt result is [1,2,3,4]<br>
TestMapToInt 学生总分为： is 300.0</p>
</div><div class="cl-preview-section"><h3 id="flatmap">2.4 flatMap</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">flatMap 方法也是可以做一些流的转化，和 map 方法不同的是，其明确了 Function 函数的返回值的泛型是流，源码如下：<br>
<img class="" src="https://img.mukewang.com/5dd6002d0001f35415580441.png" data-original="//img.mukewang.com/5dd6002d0001f35415580441.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">写了一个 demo，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testFlatMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// 计算学生所有的学习课程，flatMap 返回 List&lt;课程&gt; 格式</span>
  List<span class="token operator">&lt;</span>Course<span class="token operator">&gt;</span> courses <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">flatMap</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>s<span class="token punctuation">.</span><span class="token function">getLearningCources</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestMapToInt flatMap 计算学生的所有学习课程如下 {}"</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>courses<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 计算学生所有的学习课程，map 返回两层课程嵌套格式</span>
  List<span class="token operator">&lt;</span>List<span class="token operator">&lt;</span>Course<span class="token operator">&gt;&gt;</span> courses2 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>s<span class="token punctuation">.</span><span class="token function">getLearningCources</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestMapToInt map 计算学生的所有学习课程如下 {}"</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>courses2<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  List<span class="token operator">&lt;</span>Stream<span class="token operator">&lt;</span>Course<span class="token operator">&gt;&gt;</span> courses3 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>s<span class="token punctuation">.</span><span class="token function">getLearningCources</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestMapToInt map 计算学生的所有学习课程如下  {}"</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>courses3<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd6000a00011d6317510627.png" data-original="//img.mukewang.com/5dd6000a00011d6317510627.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><h3 id="distinct">2.5 distinct</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">distinct 方法有去重的功能，我们写了一个 demo，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testDistinct</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// 得到学生所有的名字，要求是去重过的</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> beforeNames <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getName<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestDistinct 没有去重前的学生名单 {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>beforeNames<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> distinctNames <span class="token operator">=</span> beforeNames<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">distinct</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestDistinct 去重后的学生名单 {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>distinctNames<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 连起来写</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> names <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getName<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">distinct</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestDistinct 去重后的学生名单 {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>names<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd5fff000012e9a14840706.png" data-original="//img.mukewang.com/5dd5fff000012e9a14840706.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><h3 id="sorted">2.6 Sorted</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Sorted 方法提供了排序的功能，并且允许我们自定义排序，demo 如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testSorted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// 学生按照学号排序</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> beforeCodes <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestSorted 按照学号排序之前 {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>beforeCodes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> sortedCodes <span class="token operator">=</span> beforeCodes<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sorted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestSorted 按照学号排序之后 is {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>sortedCodes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 直接连起来写</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> codes <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">)</span>
      <span class="token comment">// 等同于 .sorted(Comparator.naturalOrder()) 自然排序</span>
      <span class="token punctuation">.</span><span class="token function">sorted</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestSorted 自然排序 is {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>codes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 自定义排序器</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> codes2 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">)</span>
      <span class="token comment">// 反自然排序</span>
      <span class="token punctuation">.</span><span class="token function">sorted</span><span class="token punctuation">(</span>Comparator<span class="token punctuation">.</span><span class="token function">reverseOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestSorted 反自然排序 is {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>codes2<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd5ffd300010f9711840242.png" data-original="//img.mukewang.com/5dd5ffd300010f9711840242.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><h3 id="peek">2.7 peek</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">peek 方法很简单，我们在 peek 方法里面做任意没有返回值的事情，比如打印日志，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java">students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">peek</span><span class="token punctuation">(</span>s <span class="token operator">-</span><span class="token operator">&gt;</span> log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"当前循环的学号是{}"</span><span class="token punctuation">,</span>s<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="limit">2.8 limit</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">limit 方法会限制输出值个数，入参是限制的个数大小，demo 如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testLimit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> beforeCodes <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestLimit 限制之前学生的学号为 {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>beforeCodes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> limitCodes <span class="token operator">=</span> beforeCodes<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span>2L<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestLimit 限制最大限制 2 个学生的学号 {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>limitCodes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 直接连起来写</span>
  List<span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> codes <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span>2L<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"TestLimit 限制最大限制 2 个学生的学号 {}"</span><span class="token punctuation">,</span>JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>codes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">输出结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd5ffc00001238213120222.png" data-original="//img.mukewang.com/5dd5ffc00001238213120222.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><h3 id="reduce">2.9 reduce</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">reduce 方法允许我们在循环里面叠加计算值，我们写了 demo 如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testReduce</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// 计算一下学生的总分数</span>
  Double sum <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getScope<span class="token punctuation">)</span>
      <span class="token comment">// scope1 和 scope2 表示循环中的前后两个数</span>
      <span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token punctuation">(</span>scope1<span class="token punctuation">,</span>scope2<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">&gt;</span> scope1<span class="token operator">+</span>scope2<span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token number">0D</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"总成绩为 {}"</span><span class="token punctuation">,</span>sum<span class="token punctuation">)</span><span class="token punctuation">;</span>

  Double sum1 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getScope<span class="token punctuation">)</span>
      <span class="token comment">// 第一个参数表示成绩的基数，会从 100 开始加</span>
      <span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token number">100D</span><span class="token punctuation">,</span><span class="token punctuation">(</span>scope1<span class="token punctuation">,</span>scope2<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">&gt;</span> scope1<span class="token operator">+</span>scope2<span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"总成绩为 {}"</span><span class="token punctuation">,</span>sum1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd5ffaa00012ffc10480667.png" data-original="//img.mukewang.com/5dd5ffaa00012ffc10480667.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">第二个计算出来的总成绩多了 100，是因为第二个例子中 reduce 是从基数 100 开始累加的。</p>
</div><div class="cl-preview-section"><h3 id="findfirst">2.10 findFirst</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">findFirst 表示匹配到第一个满足条件的值就返回，demo 如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">// 找到第一个叫小美同学的 ID</span>
<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testFindFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  Long id <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>StringUtils<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token string">"小美"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
       <span class="token comment">// 同学中有两个叫小美的，这里匹配到第一个就返回</span>
      <span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"testFindFirst 小美同学的 ID {}"</span><span class="token punctuation">,</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 防止空指针</span>
  Long id2 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>StringUtils<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token string">"小天"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token comment">// orElse 表示如果 findFirst 返回 null 的话，就返回 orElse 里的内容</span>
      <span class="token punctuation">.</span><span class="token function">orElse</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StudentDTO</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"testFindFirst 小天同学的 ID {}"</span><span class="token punctuation">,</span>id2<span class="token punctuation">)</span><span class="token punctuation">;</span>

  Optional<span class="token operator">&lt;</span>StudentDTO<span class="token operator">&gt;</span> student<span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>StringUtils<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token string">"小天"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">findFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// isPresent 为 true 的话，表示 value != null，即 student.get() != null</span>
  <span class="token keyword">if</span><span class="token punctuation">(</span>student<span class="token punctuation">.</span><span class="token function">isPresent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"testFindFirst 小天同学的 ID {}"</span><span class="token punctuation">,</span>student<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"testFindFirst 找不到名为小天的同学"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd5ff9300014ba507750842.png" data-original="//img.mukewang.com/5dd5ff9300014ba507750842.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><h3 id="groupingby--tomap">2.11 groupingBy &amp;&amp; toMap</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">groupingBy 是能够根据字段进行分组，toMap 是把 List 的数据格式转化成 Map 的格式，我们写了一个 demo，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testListToMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// 学生根据名字进行分类</span>
  Map<span class="token operator">&lt;</span>String<span class="token punctuation">,</span> List<span class="token operator">&lt;</span>StudentDTO<span class="token operator">&gt;&gt;</span> map1 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">groupingBy</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getName<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"testListToMap groupingBy 学生根据名字进行分类 result is Map&lt;String,List&lt;StudentDTO&gt;&gt; {}"</span><span class="token punctuation">,</span>
           JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>map1<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 统计姓名重名的学生有哪些</span>
  Map<span class="token operator">&lt;</span>String<span class="token punctuation">,</span> Set<span class="token operator">&lt;</span>String<span class="token operator">&gt;&gt;</span> map2 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">groupingBy</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getName<span class="token punctuation">,</span>
                                  Collectors<span class="token punctuation">.</span><span class="token function">mapping</span><span class="token punctuation">(</span>StudentDTO<span class="token operator">:</span><span class="token operator">:</span>getCode<span class="token punctuation">,</span>Collectors<span class="token punctuation">.</span><span class="token function">toSet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"testListToMap groupingBy 统计姓名重名结果 is {}"</span><span class="token punctuation">,</span>
           JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>map2<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 学生转化成学号为 key 的 map</span>
  Map<span class="token operator">&lt;</span>String<span class="token punctuation">,</span> StudentDTO<span class="token operator">&gt;</span> map3 <span class="token operator">=</span> students<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
       <span class="token comment">//第一个入参表示 map 中 key 的取值</span>
       <span class="token comment">//第二个入参表示 map 中 value 的取值</span>
       <span class="token comment">//第三个入参表示，如果前后的 key 是相同的，是覆盖还是不覆盖，(s1,s2)-&gt;s1 表示不覆盖，(s1,s2)-&gt;s2 表示覆盖</span>
      <span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toMap</span><span class="token punctuation">(</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>s<span class="token punctuation">.</span><span class="token function">getCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>s<span class="token operator">-</span><span class="token operator">&gt;</span>s<span class="token punctuation">,</span><span class="token punctuation">(</span>s1<span class="token punctuation">,</span>s2<span class="token punctuation">)</span><span class="token operator">-</span><span class="token operator">&gt;</span>s1<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"testListToMap groupingBy 学生转化成学号为 key 的 map result is{}"</span><span class="token punctuation">,</span>
           JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>map3<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">运行结果如下：<br>
<img class="" src="https://img.mukewang.com/5dd5ff7900011ff615250743.png" data-original="//img.mukewang.com/5dd5ff7900011ff615250743.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">3 总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本文我们介绍了 12 种 Lambda 表达式常用的方法，大家可以找到 LambdaExpressionDemo 类，自己 debug 下，这样你在工作中遇到复杂数据结构转化时，肯定会得心应手了。</p>
</div>}
                        </div>
                    </div>
                                            <!-- 买过的阅读 -->
                        <div class="art-next-prev clearfix">
                                                                                                <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/883">
                                                                    <div class="prev l clearfix">
                                        <div class="icon l">
                                            <i class="imv2-arrow3_l"></i>
                                        </div>
                                        <p>
                                            41 突破难点：如何看 Lambda 源码  
                                        </p>
                                    </div>
                                </a>
                                                                                                                            <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/885">
                                                                    <div class="next r clearfix">
                                        <p>
                                            43 ThreadLocal 源码解析   
                                        </p>
                                        <div class="icon r">
                                            <i class="imv2-arrow3_r"></i>
                                        </div>

                                    </div>
                                </a>
                                                    </div>
                                    </div>
                <div class="comments-con js-comments-con" id="coments_con">
                </div>

                
            </div>
            
            
            

        </div>
    </div>
</div>

<div class="modal modal-jiaQun-new hide" id="modal-jiaQun">
    <div class="inner" style="">
        <div class="modal-close js-close-jiaQun">
            <i class="imv2-close"></i>
        </div>
        <div class="content">
            <img src="https://img2.mukewang.com/5d634d40000119e505400602.jpg">
            <div class="right-info">
                <div class="title">
                    扫码加入慕课Java核心用户群
                </div>
                <div class="desc">
                                            <p class="mb6">验证信息：<span id="joincode">1909271435058473</span><span class="copy js-copy-joincode">复制</span></p>
                                        <p class="mb6">QQ讨论群号：906691736</p>
                                            <p>QQ群URL：<a href="https://jq.qq.com/?_wv=1027&amp;k=55RtSbJ" target="_blank">点击访问</a></p>
                                    </div>
            </div>
            <p class="tip">若遇到搜索不到QQ群或加群失败，请联系客服邮箱:kf@imooc.com</p>
        </div>
    </div>
</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>